/****************************************************************************************************
* 版权所有： Copyright (c) 2015-2022 鑫光家纺. All rights reserved.
* 作    者： 半   饱
* 创建日期： 2022/8/8
* 界面功能： <#界面功能#>
****************************************************************************************************/
#import "BBAlertViewController.h"
#import "BBAlertAction.h"
#import "BBAlertConfiguration.h"

#if __has_include(<Masonry/Masonry.h>)
#import <Masonry/Masonry.h>
#else
#import "Masonry.h"
#endif


@interface BBAlertViewController ()

#pragma mark - 界面元素

@property (nonatomic,strong) UIView *alertView;

@property (nonatomic,strong) UIView *titleView;

@property (nonatomic,strong) UILabel *titleLabel;

@property (nonatomic,strong) UIView *messageView;

@property (nonatomic,strong) UILabel *messageLabel;

@property (nonatomic,strong) UIView *acrossSpliteView;

@property (nonatomic,strong) UIView *verticalSpliteView;

#pragma mark - 内置变量

/// 事件数组
@property  (nonatomic,strong) NSMutableArray *actionArray;

/// 标题
@property (nonatomic,copy) NSString *titleString;

/// 信息
@property (nonatomic,copy) NSString *messageString;

/// 配置
@property (nonatomic,strong) BBAlertConfiguration *alertConfiguration;

@end

@implementation BBAlertViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.alertConfiguration = [BBAlertConfiguration defaultAlertViewConfiguration];
    }
    return self;
}

+ (instancetype)alertViewControllerWithTitle:(NSString *)title withMessage:(NSString *)message  withConfiguration:(nonnull BBAlertConfiguration *)alertConfiguration {
    BBAlertViewController *instance = [[self alloc] init];
//   因为现在加入自定义东西，所以有的时候不能处理
//    if (title.length < 1 && message.length < 1) {
//        NSAssert(NO, @"Title和Message必须有一个有值");
//    }
    //这个必须放在最前面，不然不能正常执行到
    instance.alertConfiguration = alertConfiguration;
    instance.titleString = title;
    instance.messageString = message;
    //设置view.backgroundColor就已经开始执行viewDidLoad方法
    instance.view.backgroundColor = [UIColor colorWithHex:0x333333 alpha:0.5f];
    instance.modalPresentationStyle =  UIModalPresentationOverCurrentContext;
    return instance;
}

- (void)addAction:(BBAlertAction *)alertAction {
    if (!self.actionArray) {
        self.actionArray = [NSMutableArray array];
    }
    if (alertAction.actionType == BBAlertActionTypeCancel) {
        [self.actionArray insertObject:alertAction atIndex:0];
    } else {
        [self.actionArray addObject:alertAction];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self layerUI];
    if (self.customContentView) {
        [self.messageView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        [self.messageView addSubview:self.customContentView];
    }
    
    if (self.customLayer) {
        self.customLayer();
    }
}

- (void)setTitleString:(NSString *)titleString {
    _titleString = titleString;
    self.titleLabel.text = titleString;
    if (titleString.length < 1) {
        self.titleLabel.hidden = YES;
    }
}

- (void)setMessageString:(NSString *)messageString {
    _messageString = messageString;
    self.messageLabel.text = messageString;
    if (messageString.length < 1) {
        self.messageLabel.hidden = YES;
    } else {
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = self.alertConfiguration.messageLineSpace;
        style.alignment = (NSInteger)self.alertConfiguration.messageTextAlignment;
        style.lineBreakMode = NSLineBreakByTruncatingTail;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:messageString];
        [attributedString addAttributes:@{NSForegroundColorAttributeName:self.alertConfiguration.messageColor,NSFontAttributeName:self.alertConfiguration.messageFont,NSParagraphStyleAttributeName:style}  range:NSMakeRange(0, messageString.length)];
        self.messageLabel.attributedText = attributedString;
    }
}

- (void)addSubUI {
    [self.view addSubview:self.alertView];
    [self.alertView addSubview:self.titleView];
    [self.titleView addSubview:self.titleLabel];
    [self.alertView addSubview:self.messageView];
    [self.messageView addSubview:self.messageLabel];
    [self.alertView addSubview:self.acrossSpliteView];
    [self.alertView addSubview:self.verticalSpliteView];
}

- (void)layerUI {
    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view.mas_centerY).with.offset(0);
        make.left.offset(self.alertConfiguration.alertViewLeftSpace);
        make.right.offset(-self.alertConfiguration.alertViewRightSpace);
    }];
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
    }];
    if (self.titleString.length < 1) {
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(20);
            make.left.offset(16);
            make.right.offset(-16);
            make.height.offset(0);
        }];
        self.titleLabel.hidden = YES;
    } else  {
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(20);
            make.left.offset(16);
            make.right.offset(-16);
            make.height.offset(33);
        }];
    }
    if (self.messageString.length < 1 && self.actionArray.count < 1) {
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(20);
            make.left.offset(16);
            make.right.offset(-16);
            make.height.offset(33);
            make.bottom.offset(-20);
        }];
    }
    
    //加入自定义确定按钮 10-26
    NSInteger offsetCount = 0;
    if (self.customConfirmButton) {
        offsetCount = 1;
    }
    
    if (self.actionArray.count + offsetCount < 1) { //加入自定义按钮处理
        [self.messageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(0);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
            make.right.offset(0);
            make.bottom.offset(0);
        }];
        [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.top.offset(0);
            make.right.offset(-16);
            make.bottom.offset(-20);
        }];
    } else {
        [self.messageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(0);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
            make.right.offset(0);
        }];
        [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
            make.right.offset(-16);
            make.bottom.offset(0);
        }];
    }
    
    if (self.actionArray.count + offsetCount == 1) {
        [self.acrossSpliteView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.equalTo(self.messageView.mas_bottom).offset(13);
            make.height.offset(self.alertConfiguration.acrossHeight);
        }];
        self.verticalSpliteView.hidden = YES;
    }
    if (self.actionArray.count + offsetCount == 2) {
        [self.acrossSpliteView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.top.equalTo(self.messageView.mas_bottom).offset(13);
            make.height.offset(self.alertConfiguration.acrossHeight);
        }];
        [self.verticalSpliteView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.acrossSpliteView.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.alertView.mas_centerX).with.offset(0);
            make.width.offset(self.alertConfiguration.verticalWidth);
            make.bottom.equalTo(self.alertView.mas_bottom).with.offset(0);
        }];
    }
    [self showActionButton];
}

- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [[UIView alloc] init];
        _alertView.backgroundColor = self.alertConfiguration.alertViewBackgroundColor;
        _alertView.layer.cornerRadius = self.alertConfiguration.cornerRadius;
        _alertView.layer.masksToBounds = YES;
        if (self.alertConfiguration.alertViewBackgroundImage) {
            self.view.contentMode = UIViewContentModeScaleAspectFit;
            _alertView.layer.contents = (__bridge id _Nullable)self.alertConfiguration.alertViewBackgroundImage.CGImage;
        }
    }
    return _alertView;
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
    }
    return _titleView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = self.alertConfiguration.titleColor;
        _titleLabel.font = self.alertConfiguration.titleFont;
        _titleLabel.textAlignment = (NSInteger)self.alertConfiguration.titleTextAlignment;
    }
    return _titleLabel;
}

- (UIView *)messageView {
    if (!_messageView) {
        _messageView = [[UIView alloc] init];
    }
    return _messageView;
}

- (UILabel *)messageLabel {
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.textColor = self.alertConfiguration.messageColor;
        _messageLabel.textAlignment = (NSInteger)self.alertConfiguration.messageTextAlignment;
        _messageLabel.lineBreakMode =  NSLineBreakByWordWrapping;
        _messageLabel.font = self.alertConfiguration.messageFont;
        _messageLabel.numberOfLines = self.alertConfiguration.messageLineCount;
    }
    return _messageLabel;
}

- (UIView *)acrossSpliteView {
    if (!_acrossSpliteView) {
        _acrossSpliteView = [[UIView alloc] init];
        _acrossSpliteView.backgroundColor = self.alertConfiguration.acrossColor;
        _acrossSpliteView.hidden = self.alertConfiguration.acrossHidden;
    }
    return _acrossSpliteView;
}

- (UIView *)verticalSpliteView {
    if (!_verticalSpliteView) {
        _verticalSpliteView = [[UIView alloc] init];
        _verticalSpliteView.backgroundColor = self.alertConfiguration.verticalColor;
        _verticalSpliteView.hidden = self.alertConfiguration.verticalHidden;
    }
    return _verticalSpliteView;
}

- (void)showActionButton {
    self.acrossSpliteView.hidden = self.alertConfiguration.acrossHidden;
    self.verticalSpliteView.hidden = self.alertConfiguration.verticalHidden;
    //加入自定义按钮 10-26
    NSInteger offsetCount = 0;
    if (self.customConfirmButton) {
        offsetCount = 1;
    }
    
    if (self.actionArray.count + offsetCount > 3) {
        NSAssert(NO, @"BBAlertViewController最多只支持三个Action");
        return;
    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.actionType == 2"];
    NSArray *tempCancelAction = [self.actionArray filteredArrayUsingPredicate:predicate];
    if (tempCancelAction.count > 1) {
        NSAssert(NO, @"BBAlertViewController最多只能设置一个Cancel Action");
        return;
    }
    
    [self.alertView addSubview:self.customConfirmButton];//无论有没有都加上这一句，因为如果为nil也不会出错。
    
    if (self.actionArray.count == 0 && offsetCount == 1) {//处理自定义按钮
        [self.customConfirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.acrossSpliteView.mas_bottom).offset(self.alertConfiguration.actionEdgeInsets.top);
            make.height.offset(self.alertConfiguration.actionHeight);
            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
            make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
        }];
    } else {
        NSMutableArray *controlArray = [NSMutableArray array];
        NSInteger index = 0;
        if (self.customConfirmButton) {
            [controlArray addObject:self.customConfirmButton];
        }
        for (BBAlertAction *itemAction in self.actionArray) {
            UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [itemButton setTitle:itemAction.actionTitle forState:UIControlStateNormal];
            itemButton.tag = 1000 + index;
            if (itemAction.actionType == BBAlertActionTypeCancel) {
                [itemButton setTitleColor:self.alertConfiguration.typeCancelColor forState:UIControlStateNormal];
                itemButton.titleLabel.font = self.alertConfiguration.typeCancelFont;
                itemButton.backgroundColor = self.alertConfiguration.typeCancelBackgroundColor;
                itemButton.layer.borderColor = self.alertConfiguration.cancelBorderColor.CGColor;
                itemButton.layer.borderWidth = self.alertConfiguration.cancelBorderWidth;
                if (self.alertConfiguration.typeCancelBackgroundImage) {
                    [itemButton setBackgroundImage:self.alertConfiguration.typeCancelBackgroundImage forState:UIControlStateNormal];
                }
            } else if (itemAction.actionType == BBAlertActionTypeDefault) {
                [itemButton setTitleColor:self.alertConfiguration.typeDefaultColor forState:UIControlStateNormal];
                itemButton.titleLabel.font = self.alertConfiguration.typeDefaultFont;
                itemButton.backgroundColor = self.alertConfiguration.typeDefaultBackgroundColor;
                itemButton.layer.borderColor = self.alertConfiguration.defaultBorderColor.CGColor;
                itemButton.layer.borderWidth = self.alertConfiguration.defaultBorderWidth;
                if (self.alertConfiguration.typeDefaultBackgroundImage) {
                    [itemButton setBackgroundImage:self.alertConfiguration.typeDefaultBackgroundImage forState:UIControlStateNormal];
                }
            } else {
                [itemButton setTitleColor:self.alertConfiguration.typeCustomColor forState:UIControlStateNormal];
                itemButton.titleLabel.font = self.alertConfiguration.typeCustomFont;
                itemButton.backgroundColor = self.alertConfiguration.typeCustomBackgroundColor;
                itemButton.layer.borderColor = self.alertConfiguration.customBorderColor.CGColor;
                itemButton.layer.borderWidth = self.alertConfiguration.customBorderWidth;
                if (self.alertConfiguration.typeCustomBackgroundImage) {
                    [itemButton setBackgroundImage:self.alertConfiguration.typeCustomBackgroundImage forState:UIControlStateNormal];
                }
            }
            if (itemAction.actionIconImage != nil) {
                UIImage *actionImage = [itemAction.actionIconImage imageScaleWithSize:self.alertConfiguration.actionImageSize];
                [itemButton setImage:actionImage forState:UIControlStateNormal];
            }
            itemButton.layer.masksToBounds = YES;//有些影响性能，但可以把背景图片也同样切成圆角
            itemButton.layer.cornerRadius = self.alertConfiguration.actionCornerRadius;
            [itemButton addTarget:self action:@selector(itemButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
            [self.alertView addSubview:itemButton];
            
            if (self.actionArray.count + offsetCount == 1) {
                [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.acrossSpliteView.mas_bottom).offset(self.alertConfiguration.actionEdgeInsets.top);
                    make.height.offset(self.alertConfiguration.actionHeight);
                    make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
                    make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
                    make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
                }];
                [itemButton buttonWithEdgeInsetsStyle:itemAction.actionEdgeInsetStyle withImageTitleSpace:itemAction.textAndImageSpace];
            } else {
                if (self.alertConfiguration.actionDirection == BBActionDirectionVertical) {
                    if (itemAction.actionType == BBAlertActionTypeCancel && self.customConfirmButton) {
                        [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.acrossSpliteView.mas_bottom).offset((self.alertConfiguration.actionHeight + self.alertConfiguration.actionSpace) * index + self.alertConfiguration.actionEdgeInsets.top * (index +1));
                            make.height.offset(self.alertConfiguration.actionHeight);
                            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
                            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
//                            if (index == self.actionArray.count - 1) {
//                                make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
//                            }
                        }];
                        [itemButton buttonWithEdgeInsetsStyle:itemAction.actionEdgeInsetStyle withImageTitleSpace:itemAction.textAndImageSpace];
                        
                        [self.customConfirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.acrossSpliteView.mas_bottom).offset((self.alertConfiguration.actionHeight + self.alertConfiguration.actionSpace) * 1 + self.alertConfiguration.actionEdgeInsets.top * (1 +1));
                            make.height.offset(self.alertConfiguration.actionHeight);
                            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
                            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
                            make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
                        }];
                    } else if (itemAction.actionType != BBAlertActionTypeCancel && self.customConfirmButton) {
                        [self.customConfirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.acrossSpliteView.mas_bottom).offset(self.alertConfiguration.actionEdgeInsets.top);
                            make.height.offset(self.alertConfiguration.actionHeight);
                            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
                            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
                        }];
                        // index + 1 是因为第一个是self.customConfirmButton
                        [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.acrossSpliteView.mas_bottom).offset((self.alertConfiguration.actionHeight + self.alertConfiguration.actionSpace) * (index +1 ) + self.alertConfiguration.actionEdgeInsets.top * ((index + 1) +1));
                            make.height.offset(self.alertConfiguration.actionHeight);
                            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
                            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
                            if (index == self.actionArray.count - 1) {
                                make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
                            }
                        }];
                        [itemButton buttonWithEdgeInsetsStyle:itemAction.actionEdgeInsetStyle withImageTitleSpace:itemAction.textAndImageSpace];
                    } else {
                        [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(self.acrossSpliteView.mas_bottom).offset((self.alertConfiguration.actionHeight + self.alertConfiguration.actionSpace) * index + self.alertConfiguration.actionEdgeInsets.top * (index +1));
                            make.height.offset(self.alertConfiguration.actionHeight);
                            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
                            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
                            if (index == self.actionArray.count - 1) {
                                make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
                            }
                        }];
                        [itemButton buttonWithEdgeInsetsStyle:itemAction.actionEdgeInsetStyle withImageTitleSpace:itemAction.textAndImageSpace];
                    }
                } else {
                    if (itemAction.actionType == BBAlertActionTypeCancel) {
                        [controlArray insertObject:itemButton atIndex:0];
                    } else {
                        [controlArray addObject:itemButton];
                    }
                }
            }
            index++;
        }
        //按钮布局
        if (controlArray.count > 1) {
            [controlArray mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:self.alertConfiguration.actionEdgeInsets.left leadSpacing:self.alertConfiguration.actionEdgeInsets.right tailSpacing:self.alertConfiguration.actionEdgeInsets.right];
            [controlArray mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.acrossSpliteView.mas_bottom).offset(self.alertConfiguration.actionEdgeInsets.top);
                make.height.offset(self.alertConfiguration.actionHeight);
                make.bottom.mas_equalTo(self.alertView.mas_bottom).offset(-self.alertConfiguration.actionEdgeInsets.bottom);
            }];
        }
        //布局按钮前面的图片
        for (NSInteger i = 0 ; i < self.actionArray.count; i++) {
            UIButton *tmpButton = [self.alertView viewWithTag:1000 + i];
            BBAlertAction *alertAction = self.actionArray[i];
            if ([tmpButton isKindOfClass:[UIButton class]]) {
                if (alertAction.actionIconImage) {
                    [tmpButton buttonWithEdgeInsetsStyle:alertAction.actionEdgeInsetStyle withImageTitleSpace:alertAction.textAndImageSpace];
                }
            }
        }
    }
}

- (void)itemButtonEvent:(UIButton *)sender {
    BBAlertAction *alertAction  = self.actionArray[sender.tag - 1000];
    if (alertAction.actionType != BBAlertActionTypeCustom) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    if (alertAction.actionBlock) {
        dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC);
        dispatch_after(timer, dispatch_get_main_queue(), ^{
            alertAction.actionBlock();
        });
    }
}

- (void)setCustomContentView:(UIView *)customContentView {
    _customContentView = customContentView;;
}

@end
